<template>
  <div class="post-container">
    <el-card class="post-card">
      <el-form :model="postForm" label-width="80px" :rules="postRules" ref="postFormRef">
        <el-form-item label="标题" prop="postTitle">
          <el-input v-model="postForm.title" placeholder="请输入标题" />
        </el-form-item>
        
        <el-form-item label="内容" prop="postContent">
          <el-input 
            v-model="postForm.content" 
            type="textarea" 
            :rows="10"
            placeholder="请输入内容"
          />
        </el-form-item>
        
        <el-form-item label="板块" prop="boards">
          <el-select 
            v-model="postForm.boards" 
            multiple
            placeholder="请选择板块"
            style="width: 100%"
          >
            <el-option 
              v-for="board in boardList" 
              :key="board.id" 
              :label="board.name" 
              :value="board.id"
              :class="{ 'selected-board': postForm.boards.includes(board.id) }"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitPost"
            :loading="submitting"
          >
            {{ isEditMode ? '保存修改' : '发布问题' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getPostByIdService, createPostService, updatePostService } from '@/apis/post'
import { getBoardListService } from '@/apis/board'

export default {
  name: 'Post',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const postFormRef = ref(null)
    
    const postForm = ref({
      userId: '',
      postId: '',
      title: '',
      content: '',
      boards: [],
      boardId: []
    })
    
    const postRules = {
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
      boards: [{ required: true, message: '请选择至少一个板块', trigger: 'change' }]
    }
    
    const boardList = ref([])
    const submitting = ref(false)
    const isEditMode = ref(false)
    
    const fetchPost = async (postId) => {
      try {
        const res = await getPostByIdService(postId)
          postForm.value = {
            ...res,
            boards: res.boards ? res.boards.map(board => {
              if (typeof board === 'string') return board;
              return board?.boardName || board?.name || '';
            }) : [],
            boardId: res.boards ? res.boards.map(board => {
              if (typeof board === 'string') return board;
              return board?.boardId || board?.id || '';
            }) : []
          }
      } catch (error) {
        console.error('获取帖子失败:', error)
        ElMessage.error(error.message)
      }
    }
    
    const fetchBoardList = async () => {
      try {
        const res = await getBoardListService()
        if (res.code === 1000) {
          boardList.value = res.rows.map(item => ({
            id: item?.boardId || item?.id || '',
            name: item?.boardName || item?.name || ''
          }))
        } else {
          throw new Error(res.msg || '获取板块列表失败或数据格式不正确')
        }
      } catch (error) {
        console.error('获取板块列表失败:', error)
        ElMessage.error(error.message)
      }
    }
    
    const submitPost = async () => {
      try {
        await postFormRef.value.validate()
        
        await ElMessageBox.confirm(
          '确定要修改这个帖子吗？',
          '确认修改',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        submitting.value = true
        
        const postData = {
          boardId: postForm.value.boards,
          postId: postForm.value.postId,
          title: postForm.value.title,
          content: postForm.value.content,
          userId: postForm.value.userId
        }
        
        let res
        if (isEditMode.value) {
          res = await updatePostService(postData)
        } else {
          res = await createPostService(postData)
        }
        
        if (res.code === 1000) {
          ElMessage.success(isEditMode.value ? '修改成功' : '发布成功')
          if (isEditMode.value) {
            router.push(`/forum/detail/${postForm.value.postId}`)
          }
        } else {
          throw new Error(res.msg || isEditMode.value ? '修改失败' : '发布失败')
        }
      } catch (error) {
        if (error.message === '验证失败') {
          return
        }
        if (error !== 'cancel') {
          console.error('操作失败:', error)
          ElMessage.error(error.message)
        }
      } finally {
        submitting.value = false
      }
    }
    
    onMounted(() => {
      fetchBoardList()
      
      const postId = route.query.postId
      isEditMode.value = route.query.editMode === 'true'
      
      if (postId && isEditMode.value) {
        fetchPost(postId)
      }
    })
    
    return {
      postForm,
      postFormRef,
      postRules,
      boardList,
      submitting,
      isEditMode,
      submitPost
    }
  }
}
</script>

<style scoped>
.post-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.post-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-select-dropdown__item.selected-board {
  background-color: #f0f9eb;
  color: #67c23a;
}

.el-select-dropdown__item:not(.selected-board) {
  background-color: #f5f7fa;
  color: #909399;
}
</style>